//模拟日志上报

package main

import (
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"
)

type Tracker struct {
	wg sync.WaitGroup
}

func (t *Tracker) Event(data string) {
	t.wg.Add(1)

	//干一些其他的事情

	//真是的日志上报
	go func() {
		defer t.wg.Done()
		time.Sleep(time.Millisecond)
		fmt.Printf("data : %s\n", data)
	}()
}

func (t *Tracker) Shutdown() {
	t.wg.Wait()
}

type App struct {
	track *Tracker
}

func (a *App) Handle(writer http.ResponseWriter, request *http.Request) {
	//writer.WriteHeader(http.StatusCreated)
	fmt.Fprintln(writer, "Hello world")
	a.track.Event("log data")
}

func main() {
	//这个demo的问题在于如果日上上报时间过长，main函数始终退不出
	t := Tracker{}

	a := App{
		track: &t,
	}

	http.HandleFunc("/", a.Handle)

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}

	a.track.Shutdown()
}
